<template>
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px;">
    <div class="grid-container">
        <el-form-item label="品牌编号">
            <el-input v-model="state.dataForm.brandCode" type="text" clearable placeholder="请输入品牌编号"></el-input>
        </el-form-item>
        <el-form-item label="品牌名称">
            <el-input v-model="state.dataForm.brandName" type="text" clearable placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="产地">
            <el-select v-model="state.dataForm.brandClassId" placeholder="请选择产地" clearable>
                <el-option v-for="option in brandClassifyOptions" :key="option.id" :label="option.className"
                    :value="option.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="是否首页推荐">
            <el-select v-model="state.dataForm.tuijianFlag" placeholder="请选择" clearable>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="是否首页展示">
            <el-select v-model="state.dataForm.showFlag" placeholder="请选择" clearable>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
            </el-select>
        </el-form-item>
    </div>
        <div  style="text-align: right;">
            <!-- 查询 -->
            <el-form-item>
                <el-button @click="state.getDataList()"
                    style="background: rgba(22, 119, 255, 1);color: #fff;border-radius: 5px;">{{ $t("query")
                    }}</el-button>
            </el-form-item>
            <!-- 重置 -->
            <el-form-item>
                <el-button @click="resetForm"
                    style="background: rgba(239, 244, 255, 1);border: 1px solid rgba(16, 98, 202, 1);color: #1062CA;border-radius: 5px;">重置</el-button>
            </el-form-item>
            <!--新增-->
            <el-form-item>
                <el-button @click="addOrUpdateHandle()" v-if="state.hasPermission('base:brand:save')"
                    style="background: rgba(22, 119, 255, 1);color: #fff;width: 100px;border-radius: 5px;">{{ $t("add")
                    }}</el-button>
            </el-form-item>
             <!--新增-->
             <el-form-item>
                <el-button @click="mergeHandle()" v-if="state.hasPermission('base:brand:merge')"
                    style="background: rgba(22, 119, 255, 1);color: #fff;width: 100px;border-radius: 5px;">品牌合并</el-button>
            </el-form-item>
            <!--导出-->
            <el-form-item>
                <el-button @click="exportBrands" v-if="state.hasPermission('base:brand:export')"
                    style="background: rgba(22, 119, 255, 1);color: #fff;width: 100px;border-radius: 5px;">导出</el-button>
            </el-form-item>
        </div>

        <el-table :header-cell-style="{ 'background': '#eef1f6', 'color': '#1f2d3d', 'border-color': '#dfe6ec' }"
            v-loading="state.dataListLoading" :data="state.dataList" border
            @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
            <el-table-column align="center" prop="brandCode" label="品牌编号" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="brandName" label="品牌名称" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="brandClassifyName" label="产地" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="seriesCount" label="产品系列数量" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="userCount" label="供应商数量" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="tuijianFlag" label="是否首页推荐" width="120" show-overflow-tooltip>
              <template v-slot="scope">
                <span v-if="scope.row.tuijianFlag === 1" style="color: #67C23A">是</span>
                <span v-else-if="scope.row.tuijianFlag === 0" style="color: #F56C6C">否</span>
              </template>
          </el-table-column>
          <el-table-column align="center" prop="showFlag" label="是否首页展示" width="120" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.showFlag === 1" style="color: #67C23A">是</span>
              <span v-else-if="scope.row.showFlag === 0" style="color: #F56C6C">否</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="createUsername" label="创建人" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="createAt" label="创建时间" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="updateUsername" label="更新人" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="updateAt" label="更新时间" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column fixed="right" align="center" prop="" label="操作" width="280">
              <template v-slot="scope">
                  <el-button link type="primary" v-if="state.hasPermission('base:brand:update')"
                      @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
                  <el-button link v-if="scope.row.imgUrl"
                      @click="previewImage(scope.row)">图片预览</el-button>
                  <el-button link type="danger" v-if="state.hasPermission('base:brand:dalete')"
                      @click="state.deleteHandle(scope.row.id)">{{ $t("delete")
                            }}</el-button>
              </template>
          </el-table-column>
        </el-table>
    </el-form>
    <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
        :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
        @current-change="state.pageCurrentChangeHandle"> </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update :key="addKey" ref="addOrUpdateRef" @refreshDataList="refreshDataList"></add-or-update>
    <!-- 品牌合并弹窗 -->
    <brand-merge :key="mergeKey" ref="brandMergeRef" @refreshDataList="refreshDataList"></brand-merge>
  <!-- 弹窗, 图片预览 -->
  <el-dialog v-model="previewDialogVisible" title="图片预览" width="30%" center>
    <img :src="previewImageUrl" alt="预览图片" style="width: 100%; height: auto;" />
  </el-dialog>
</template>
<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus"
import { useRouter } from 'vue-router'
import useView from "@/hooks/useView";
import { nextTick, reactive, ref, toRefs, watch } from "vue";
import AddOrUpdate from "./brand-list-add-or-update.vue";
import BrandMerge from "./brand-merge.vue";
import app from "@/constants/app";
import { ElMessageBox } from "element-plus";

// 注册组件
const components = {
    AddOrUpdate,
    BrandMerge
};
// 图片预览弹窗状态
const previewDialogVisible = ref(false);
const previewImageUrl = ref('');
const view = reactive({
    getDataListURL: '/base/basebrand/page',
    getDataListIsPage: true,
    deleteURL: "/base/basebrand/delete",
    deleteIsBatch: true,
    dataForm: {
        id: "",
        brandCode: "",
        brandName: "",
        brandClassId: "",
        tuijianFlag: "",
        showFlag: ""
    },
});

// 重置表单
const resetForm = () => {
    view.dataForm.brandCode = "";
    view.dataForm.brandName = "";
    view.dataForm.brandClassId = "";
    view.dataForm.tuijianFlag = "";
    view.dataForm.showFlag = "";
    state.getDataList();
};
const deleteHandle = (id?: string) => {
    baseService.post(view.deleteURL, { id: id }).then((res) => {
      if (res && res.code === 0) {
        ElMessage.success("删除成功");
        state.getDataList();
      } else {
        ElMessage.error(res.msg);
      }
    });
    return ;
};
// 导出品牌
const exportBrands = () => {
    // 创建一个隐藏的a标签用于下载
    const link = document.createElement('a');
    // link.href = `${baseService.baseUrl}/base/basebrand/export`;
    link.href = `${app.api}/base/basebrand/export`
      +'?order=&orderField=&page=1&limit=50000'
      +'&id='+ view.dataForm.id
      +'&brandCode=' + view.dataForm.brandCode
      +'&brandName=' + view.dataForm.brandName
      +'&brandClassId=' + view.dataForm.brandClassId
      +'&tuijianFlag=' + view.dataForm.tuijianFlag
      +'&showFlag=' + view.dataForm.showFlag
    // link.href = `${import.meta.env.VITE_APP_BASE_API}/base/basebrand/export`;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};


//图片预览
const previewImage = (row: any) => {
  if (row.imgUrl) {
    previewImageUrl.value = row.imgUrl;
    previewDialogVisible.value = true;
  } else {
    ElMessage.warning('该品牌没有图片');
  }
};

//新增
const addKey = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number) => {
    addKey.value++;
    nextTick(() => {
        addOrUpdateRef.value.init(id,);
    });
};

//品牌合并
const mergeKey = ref(0);
const brandMergeRef = ref();
const mergeHandle = () => {
    mergeKey.value++;
    nextTick(() => {
        brandMergeRef.value.init();
    });
};

//刷新数据
const refreshDataList = () => {
    state.refreshDataList();
};

const state = reactive({ ...useView(view), ...toRefs(view) });
state.limit = 20;

// 产地选项
const brandClassifyOptions = ref<any[]>([]);
// 获取分类列表
const getBrandClassifyList = () => {
    baseService.get('/base/basebrandclassify/queryList2').then(res => {
        // 确保数据结构符合级联选择器要求
        brandClassifyOptions.value = res.data;
        console.log('产地数据加载成功:', brandClassifyOptions.value);
    }).catch(error => {
        console.error('获取分类数据出错:', error);
        ElMessage.error('获取分类数据出错');
    });
};
getBrandClassifyList();
</script>
<style lang="scss" scoped>
::v-deep .el-table .cell {
    white-space: nowrap;
    font-size: 13px;
    height: 25px;
}


.el-input {
    width: 218px;
    height: 32px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(255, 255, 255, 1);
}
.grid-container{
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); /* 自动适应列宽，每列至少200px */
    gap: 16px; /* 元素间距 */
}

</style>
